import { debug } from './utils/debug.js'
import { setupAutomation } from './automation/automation.js'
import {
  setupSettings,
  formatApiUrl,
  loadSettings,
  saveSettings,
} from './settings/settings.js'
import { sendMessage } from './api/api.js'
import { setupChat } from './chat/chat.js'
import { executeTool } from './tools/tools.js'

document.addEventListener('DOMContentLoaded', () => {
  const apiUrl = document.getElementById('apiUrl')
  const apiKey = document.getElementById('apiKey')
  const saveSettingsBtn = document.getElementById('saveSettings')
  const userInput = document.getElementById('userInput')
  const sendBtn = document.getElementById('sendBtn')
  const chatHistory = document.getElementById('chatHistory')
  const toggleSettings = document.getElementById('toggleSettings')
  const settingsPanel = document.getElementById('settingsPanel')
  const automationBtn = document.getElementById('automationBtn')

  // 初始化各个模块
  setupAutomation(automationBtn)
  setupSettings(toggleSettings, settingsPanel)
  loadSettings(apiUrl, apiKey, debug)
  saveSettings(apiUrl, apiKey, saveSettingsBtn, debug)
  setupChat(sendBtn, userInput, chatHistory, (message) =>
    sendMessage(message, debug, appendMessage)
  )
})

// 添加消息到聊天历史
function appendMessage(message, isUser) {
  const messageDiv = document.createElement('div')
  messageDiv.className = `message ${isUser ? 'user-message' : 'ai-message'}`

  // 添加时间戳
  const timestamp = document.createElement('div')
  timestamp.className = 'timestamp'
  timestamp.textContent = new Date().toLocaleTimeString()

  // 渲染Markdown并处理代码块
  const formattedMessage = message.replace(/\n/g, '<br>')
  messageDiv.innerHTML = marked.parse(formattedMessage)

  // 添加复制按钮
  const copyBtn = document.createElement('button')
  copyBtn.className = 'copy-btn'
  copyBtn.textContent = '复制'
  copyBtn.onclick = () => {
    navigator.clipboard.writeText(message)
    copyBtn.textContent = '已复制!'
    setTimeout(() => (copyBtn.textContent = '复制'), 2000)
  }

  // 添加加载状态
  if (!isUser) {
    const loading = document.createElement('div')
    loading.className = 'loading'
    messageDiv.appendChild(loading)
    setTimeout(() => loading.remove(), 1000) // 模拟加载完成
  }

  messageDiv.appendChild(timestamp)
  messageDiv.appendChild(copyBtn)
  chatHistory.appendChild(messageDiv)
  chatHistory.scrollTop = chatHistory.scrollHeight

  // 保存消息到历史记录
  chrome.storage.local.get(['chatHistory'], (result) => {
    const history = result.chatHistory || []
    history.push({
      message: message,
      isUser: isUser,
      timestamp: new Date().toISOString(),
    })
    chrome.storage.local.set({ chatHistory: history })
  })
}
